package com.burgeon.backend.EnterpriseWeChat.service.Impl;

import com.burgeon.backend.EnterpriseWeChat.entity.*;
import com.burgeon.backend.EnterpriseWeChat.rest.Brand.*;
import com.burgeon.backend.EnterpriseWeChat.rest.action.ActionRest;
import com.burgeon.backend.EnterpriseWeChat.service.EWBrandService;
import com.burgeon.backend.EnterpriseWeChat.service.ex.UpDataException;
import com.burgeon.backend.EnterpriseWeChat.utils.ChineseInital;
import com.burgeon.backend.EnterpriseWeChat.utils.TestUrlUtils;
import com.burgeon.backend.SHOP.service.util.AddressUtil;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class EWBrandServiceImpl implements EWBrandService {
    private final static Log logger = LogFactory.getLog(EWBrandService.class);
    @Autowired
    private AccountMapper accountMapper;

    /**
     * 云仓库存
     * @param token
     * @param dimId1
     * @param dimId2
     * @param dimId3
     * @param dimId4
     * @return
     */
    @Override
    public ArrayList<Product> getYuncangInventory(String token, String dimId1, String dimId2,
                                                  String dimId3, String dimId4,String dimId5,String dimId6, int page) {
        Info info = GetInfoByToken(token);
        getYuncangInventory getYuncangInventory = new getYuncangInventory(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<Product> productList= new ArrayList<>();
        try {
            ArrayList<Product> productInventories = getYuncangInventory.getData(dimId1, dimId2, dimId3, dimId4,
                    dimId5,dimId6, page);
            //判断云仓图片是否能链接可用
            for (com.burgeon.backend.EnterpriseWeChat.entity.Product Product :productInventories) {
                String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + Product.getProductName()+".jpg";
                String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + Product.getProductName()+".png";
                if(TestUrlUtils.testUrl(jpgUrl)){
//                    System.err.println(jpgUrl);
                    Product.setProductUrl(jpgUrl);
                }else if (TestUrlUtils.testUrl(pngUrl)){
//                    System.err.println(pngUrl);
                    Product.setProductUrl(pngUrl);
                }else {
                    Product.setProductUrl("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                }
                productList.add(Product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("云仓库存"+e.getMessage());
        }
        return productList;
    }

    /**
     * 云仓推荐
     * @param token
     * @param dimId1
     * @param dimId2
     * @param dimId3
     * @param dimId4
     * @param timeSpan
     * @return
     */
    @Override
    public ArrayList<Product> getYuncangHot(String token, String dimId1, String dimId2, String dimId3, String dimId4,
                                            String dimId5,String dimId6, String timeSpan, int page) {
        Info info = GetInfoByToken(token);
        getYuncangHot getYuncangHot = new getYuncangHot(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<Product> productList= new ArrayList<>();
        try {
            ArrayList<Product> productInventories = getYuncangHot.getData(dimId1, dimId2, dimId3, dimId4,dimId5,dimId6, timeSpan,page);
            //判断云仓图片是否能链接可用
            for (com.burgeon.backend.EnterpriseWeChat.entity.Product Product :productInventories) {
                String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + Product.getProductName()+".jpg";
                String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + Product.getProductName()+".png";
                if(TestUrlUtils.testUrl(jpgUrl)){
//                    System.err.println(jpgUrl);
                    Product.setProductUrl(jpgUrl);
                }else if (TestUrlUtils.testUrl(pngUrl)){
//                    System.err.println(pngUrl);
                    Product.setProductUrl(pngUrl);
                }else {
                    Product.setProductUrl("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                }
                productList.add(Product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("云仓推荐"+e.getMessage());
        }
        return productList;
    }

    /**
     * 购物车推荐
     * @param token
     * @return
     */
    @Override
    public ArrayList<Product> getRecommandList(String token, String contend, int page ) {
        Info info = GetInfoByToken(token);
        getRecommandList getRecommandList = new getRecommandList(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<Product> productList= new ArrayList<>();
        ActionRest actionRest = new ActionRest(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            actionRest.getData("APP_RETAILRELATION_GENERATE");
            ArrayList<Product> products = getRecommandList.getData(contend,page);
            for (Product product:products) {
                String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".jpg";
                String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".png";
                if(TestUrlUtils.testUrl(jpgUrl)){
                    System.err.println(jpgUrl);
                    product.setProductUrl(jpgUrl);
                }else if (TestUrlUtils.testUrl(pngUrl)){
                    System.err.println(pngUrl);
                    product.setProductUrl(pngUrl);
                }else {
                    System.err.println(product.getProductName());
                    System.err.println("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                    product.setProductUrl("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                }
                productList.add(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("购物车推荐"+e.getMessage());
        }
        return productList;
    }

    /**
     * 筛选条件
     * @param token
     * @param dimFlag
     * @return
     */
    @Override
    public ArrayList<DimDef> getFilterData(String token, String dimFlag, int page) {
        Info info = GetInfoByToken(token);
        ArrayList<DimDef> dimDefs= new ArrayList<>();
        getFilterData getFilterData = new getFilterData(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            dimDefs = getFilterData.getData(dimFlag,page);
            if(page ==0){
                for (DimDef dimDef:dimDefs) {
                    ChineseInital cte = new ChineseInital();
                    String first = cte.getFirstLetter(dimDef.getAttribName()).toUpperCase();
                    if (is_alpha(first)){
                        dimDef.setInitial(first);
                    }else {
                        dimDef.setInitial("#");
                    }
//                    System.err.println(dimDef.getInitial());

                }
                Collections.sort(dimDefs, new SortByAge2());

            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("筛选条件"+e.getMessage());
        }
        return dimDefs;
    }

    @Override
    public ArrayList<DIM> getDIMData(String token) {
        Info info = GetInfoByToken(token);
        ArrayList<DIM> dims= new ArrayList<>();
        getDIMData getDIMData = new getDIMData(info.getUrl(),info.getAccount(),info.getPassword());
            try {
//                String dimId1 ="1";
//                String dimId2 ="4";
//                String dimId3 ="5";
//                String dimId4 ="6";
                String[] dimIds = {"1","2","3","4","5","6"};
                for (String d:dimIds) {
                    DIM dim1 = getDIMData.getData(d);
                    dims.add(dim1);
                }
//                DIM dim1 = getDIMData.getData(dimId1);
//                dims.add(dim1);
//                DIM dim2 = getDIMData.getData(dimId1);
//                dims.add(dim2);
//                DIM dim3 = getDIMData.getData(dimId1);
//                dims.add(dim3);
//                DIM dim4 = getDIMData.getData(dimId1);
//                dims.add(dim4);
                System.err.println(dims);
                return dims;
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
                throw new UpDataException(e.getMessage());
            }

    }

    public static boolean isInteger(String str) {
//        String str = "B";
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /**

     * 判断是否是字母

     * @param str 传入字符串

     * @return 是字母返回true，否则返回false

     */

    public boolean is_alpha(String str) {

        if(str==null) return false;

        return str.matches("[a-zA-Z]+");

    }

    /**
     * 货号或品名，云仓库存搜索
     * @param token
     * @param content
     * @return
     */
    @Override
    public ArrayList<Product> FindYuncangInventory(String token, String content, int page) {
        Info info = GetInfoByToken(token);
        ArrayList<Product> productList= new ArrayList<>();
        FindYuncangInventory findYuncangInventory= new FindYuncangInventory(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            ArrayList<Product> products = findYuncangInventory.getData(content,page);
            for (Product product:products) {
                //判断商品的图片是否可以连接
                String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".jpg";
                String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" + product.getProductName()+".png";
                if(TestUrlUtils.testUrl(jpgUrl)){
                    System.err.println(jpgUrl);
                    product.setProductUrl(jpgUrl);
                }else if (TestUrlUtils.testUrl(pngUrl)){
                    System.err.println(pngUrl);
                    product.setProductUrl(pngUrl);
                }else {
                    product.setProductUrl("http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/product.png");
                }
                productList.add(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpDataException("搜索错误"+e.getMessage());
        }

        return productList;
    }

    @Override
    public HashMap getProductInventory(String token, String productName,String longitude,String latitude) {
        BigDecimal lon = new BigDecimal(longitude);//经度
        BigDecimal lat = new BigDecimal(latitude);
        Info info = GetInfoByToken(token);
        HashMap map = new HashMap();
        //获取款号对应的商品
        FindYuncangByProductName findYuncangByProductName = new FindYuncangByProductName(info.getUrl(),info.getAccount(),info.getPassword());
        ArrayList<StoreInventory> list= new ArrayList<>();
        getProductInventory getProductInventory = new getProductInventory(info.getUrl(),info.getAccount(),info.getPassword());
        //判断商品的图片是否可以连接
        String jpgUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" +productName+".jpg";
        String pngUrl = "http://"+info.getUrl() + "/html/M_PRODUCT/" +productName+".png";
        if(TestUrlUtils.testUrl(jpgUrl)){
            System.err.println(jpgUrl);
            map.put("productUrl",jpgUrl);
        }else if (TestUrlUtils.testUrl(pngUrl)){
            System.err.println(pngUrl);
            map.put("productUrl",pngUrl);
        }else {
            map.put("productUrl","http://lfwd.cloudsmicro.com:8080/img/EnterpriseWeChat/big.png");
        }
        Product Product = new Product();
        try {
              Product= findYuncangByProductName.getData(productName);
             list = getProductInventory.getData(productName);
             int totalInventory=0;
            for (int i= 0;i<list.size();i++) {
                totalInventory += Integer.parseInt(list.get(i).getInventory());
                if(list.get(i).getLatitude().equals("null") || list.get(i).getLongitude().equals("null")){
                    list.get(i).setDistance(0.00);
                    System.err.println(list.get(i).getDistance());
                }else {
                BigDecimal lons = new BigDecimal(list.get(i).getLongitude());
                BigDecimal lats = new BigDecimal(list.get(i).getLatitude());
                //计算距离
                double distance = AddressUtil.getDistance(lat.doubleValue(), lon.doubleValue(), lats.doubleValue(), lons.doubleValue());
                list.get(i).setDistance((double) Math.round(distance * 100) / 100);//保留一位小数 四舍五入
//                    System.err.println(list.get(i).getDistance());

                }
            }
            //总库存
            Product.setTotalInventory(totalInventory);
            //排序
            Collections.sort(list, new SortByAge());

        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("storeList",list);
        map.put("product",Product);
        return map;
    }

    @Override
    public ArrayList<ProductItem> getStoreInventory(String token, String productName, String storeId) {
        Info info = GetInfoByToken(token);
        getStoreInventory getStoreInventory = new getStoreInventory(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            ArrayList<ProductItem> productItems = getStoreInventory.getData(productName, storeId,token);
            return productItems;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }
   class SortByAge implements Comparator {
        public int compare(Object o1, Object o2) {
            StoreInventory s1 = (StoreInventory) o1;
            StoreInventory s2 = (StoreInventory) o2;

            if (s1.getDistance() > s2.getDistance())
                return 1;
            return -1;
            //不用写s1.getAge()==s2.getAge()的情况
        }
    }
    class SortByAge2 implements Comparator {
        Collator collator = Collator.getInstance(Locale.CHINA);

        public int compare(Object o1, Object o2) {
            DimDef d1 = (DimDef) o1;
            DimDef d2 = (DimDef) o2;
            CollationKey key1 = collator.getCollationKey(d1.getAttribName());
            CollationKey key2 = collator.getCollationKey(d2.getAttribName());
            return key1.compareTo(key2);
        }

    }

}

